import axios from 'axios'
import type { InternalAxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'
// import { useUserStoreHook } from '@/store/modules/user'
// import cookies from './cookie'

// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 50000,
  headers: { 'Content-Type': 'application/json;charset=utf-8' },
})

// 获取本地 token
function getToken() {
  return localStorage.getItem('token') || ''
}

// 获取本地 refreshToken
function getRefreshToken() {
  return localStorage.getItem('refreshToken') || ''
}

// 设置新 token
function setToken(token: string) {
  localStorage.setItem('token', token)
}

// 标记刷新 token 的 Promise，避免并发多次刷新
let refreshingPromise: Promise<string> | null = null

// 刷新 token 方法
async function refreshToken() {
  if (!refreshingPromise) {
    refreshingPromise = service
      .post('/auth/refresh', {
        refreshToken: getRefreshToken(),
      })
      .then((res: AxiosResponse<{ token: string }>) => {
        setToken(res.data.token)
        refreshingPromise = null
        return res.data.token
      })
      .catch((err) => {
        refreshingPromise = null
        // 刷新失败，清理 token 并跳转登录
        localStorage.removeItem('token')
        localStorage.removeItem('refreshToken')
        window.location.href = '/login'
        throw err
      })
  }
  return refreshingPromise
}

// 请求拦截器
service.interceptors.request.use(
  async (config: InternalAxiosRequestConfig) => {
    // 判断 token 是否快过期（此处假设 token 里有 exp 字段，实际可根据你的业务调整）
    let token = getToken()
    if (token) {
      try {
        const payload = JSON.parse(atob(token.split('.')[1]))
        const now = Math.floor(Date.now() / 1000)
        // 如果 5 分钟内过期则刷新
        if (payload.exp && payload.exp - now < 300) {
          token = await refreshToken()
        }
        config.headers = config.headers || {}
        config.headers['Authorization'] = `Bearer ${token}`
      } catch {
        // token 解析失败，清理并跳转登录
        localStorage.removeItem('token')
        localStorage.removeItem('refreshToken')
        window.location.href = '/login'
      }
    }
    return config
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  },
)

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { code, msg } = response.data
    if (code == '200') {
      return response.data
    }
    // 响应数据为二进制流处理(Excel导出)
    if (response.data instanceof ArrayBuffer) {
      return response
    }
    return Promise.reject(new Error(msg || 'Error'))
  },
  (error: AxiosError<{ message: string }>) => {
    error.message = error.response?.data?.message || error.message || '请求失败'
    return Promise.reject(error.message)
  },
)

// 导出 axios 实例
export default service
